<template>
  <div>
    <cusDialog ref="dialog" width="1000px" title="留样计划" headCss="float:left;" @confrim="confrimHandler"
      @hideHandler="hideHandler">
      <el-form :model="sampleForm" ref="sampleFormRef" :inline="true" :rules="rules">
        <el-form-item label="留样设备" prop="deviceId">
          <el-select v-model="sampleForm.deviceId" placeholder="请选择留样设备" style="width: 150px;">
            <el-option v-for="item in deviceList" :key="item.deviceId" :label="item.deviceName"
              :value="item.deviceId" />
          </el-select>
        </el-form-item>
        <el-form-item label="留样日期" prop="gmtCook">
          <el-date-picker v-model="sampleForm.gmtCook" type="date" format="YYYY-MM-DD" value-format="YYYY-MM-DD"
            placeholder="请选择时间" :disabled-date="disabledDate" />
        </el-form-item>
        <el-form-item label="留样餐段" prop="mealSegmentId">
          <el-radio-group v-model="sampleForm.mealSegmentId">
            <el-radio :label="item.id" v-for="(item, index) in mealList" :key="index">{{ item.mealSegmentName
              }}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>


      <el-form :inline="true">
        <el-form-item>
          <el-input v-model="dishName" placeholder="请输入菜肴名称" @keyup.enter="getDishList" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <cusButton color="#0052D9" @click="getDishList">查询</cusButton>
        </el-form-item>
      </el-form>

      <div>
        <el-tabs type="border-card" v-model="dishTypeId" @tab-click="handleClick">
          <el-tab-pane :label="item.dishTypeName" :name="item.id" v-for="(item, index) in dishTypeList" :key="index">
            <div class="dishesBox" @click="selectDishes($event)">
              <span v-for="(dishes, index) in dishesList" :key="index" class="dishesItem" :data-name="dishes.dishName"
                :data-code="dishes.dishCode">
                {{ dishes.dishName
                }}
              </span>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
      <el-divider content-position="left">已选择菜肴 (点击可删除)</el-divider>
      <div class="selectDishesBox ">
        <el-tag v-for="tag in selectedDishList" :key="tag.dishCode" closable type="warning" @close="handleClose(tag)">
          {{ tag.dishName }}
        </el-tag>
      </div>

    </cusDialog>
  </div>
</template>

<script setup lang="ts">
import { useRouter } from "vue-router";
import { reqBindDeviceList, reqCreatePlan } from "@/api/business/device";
import { reqDishList, reqDishTypeList } from "@/api/business/dishes";
const router = useRouter();

// 禁用当日以前的日期
const disabledDate = (time: Date) => {
  return time.getTime() < Date.now() - 8.64e7;
};
const dialog = ref(null);

const formOrigin = () => ({
  gmtCook: "",
  mealSegmentId: "",
  deviceId: "",
  id: '',
});

const rules = reactive({
  deviceId: { required: true, message: "此项必填", trigger: "blur" },
  mealSegmentId: { required: true, message: "此项必填", trigger: "blur" },
  gmtCook: { required: true, message: "此项必填", trigger: "blur" },
});

// 餐段列表
const mealList = ref([])

const sampleForm = ref(formOrigin());
const pageInit = () => ({
  total: 0,
  page: 1,
  pageSize: 20,
});
const pageObj = ref(pageInit());

const emits = defineEmits(["onInit"]);

const show = (arr) => {
  if (arr) {
    selectedDishList.value = arr
  }
  getBindDeviceList();
  getDishTypeList()
  dialog.value.show = true;
};

const confrimHandler = () => {
  sampleFormRef.value.validate((valid, fields) => {
    if (valid) {
      if (selectedDishList.value.length <= 0) {
        ElMessage.info('请选择菜肴')
        return false
      }
      let planDishList = [];
      selectedDishList.value.forEach(el => {
        let { dishCode } = el
        planDishList.push({
          dishCode
        })
      })
      reqCreatePlan({
        ...sampleForm.value,
        planDishList,
      }).then((res) => {
        if (res.code == 1) {
          ElMessage.success("操作成功");
          emits("onInit");
        } else {
          ElMessage.info(res.msg);
        }
      });
      dialog.value.show = false;
    }
  });
};

const sampleFormRef = ref();
// 已选择菜肴列表
const selectedDishList = ref([])
// 对话框关闭重置初始数据
const hideHandler = () => {
  sampleForm.value = formOrigin();
  sampleFormRef.value.resetFields();
  dishesList.value = [];
  selectedDishList.value = []
  dishName.value = ''
  dishTypeId.value = ''
};

const deviceList = ref([]);

// 获取设备列表
const getBindDeviceList = () => {
  reqBindDeviceList().then((res) => {
    if (res.code == 1) deviceList.value = res.data;
  });
};

const dishTypeList = ref([])
const dishTypeId = ref("")
const dishName = ref('')
// 获取菜肴类型
const getDishTypeList = () => {
  reqDishTypeList({
    currentPage: 1,
    pageSize: 3000
  }).then((res) => {
    if (res.code == 1) {
      dishTypeList.value = res.data.list;
      dishTypeList.value.unshift({ dishTypeName: '全部', id: '' })
      getDishList()
    }

  });
};
// 切换菜肴类型
const handleClick = (tab) => {
  dishTypeId.value = tab.props.name
  getDishList()
}

const dishesList = ref([]);
// 获取菜肴列表
const getDishList = () => {
  reqDishList({
    currentPage: 1,
    pageSize: 3000,
    dishName: dishName.value,
    dishTypeId: dishTypeId.value
  }).then((res) => {
    if (res.code == 1) {
      dishesList.value = res.data.list
    }
  });
};

// 选择菜肴
const selectDishes = ($event) => {
  if (!$event.target.dataset.code) return false
  let { name, code } = $event.target.dataset
  let flag = selectedDishList.value.find(el => {
    return el.dishCode == code
  })
  if (!flag) {
    selectedDishList.value.push({
      dishCode: code,
      dishName: name
    })
  } else {
    ElMessage.info('该菜肴已选，请选择其他菜肴')
  }
}

// 删除菜肴
const handleClose = (tag) => {
  // console.log(tag)
  selectedDishList.value.splice(selectedDishList.value.indexOf(tag), 1)
}

defineExpose({ show, sampleForm, mealList });
</script>

<style lang="scss" scoped>
.dishesBox {
  max-height: 300px;
  min-height: 150px;
  overflow-y: auto;

  .dishesItem {
    margin: 0 18px 8px 0;
    white-space: nowrap;
    color: #3d7fe9;
    cursor: pointer;
  }
}

.selectDishesBox {
  padding: 15px;
  width: 100%;
  height: 120px;
  overflow-y: auto;
  border: 1px solid #dcdfe6;

  .el-tag {
    margin: 0 18px 8px 0;
  }
}
</style>